﻿using K8.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class MesProductRepositories : IMesProductRepositories
{
    #region 同步方法
    public MesProduct QueryById(string objId)
    {
        var _db = Db.Default;
        return _db.MesProducts.FirstOrDefault(d => d.Id == objId);
    }

    /// <summary>
    /// 功能描述:根据ID查询数据
    /// 作　　者:Robin
    /// </summary>
    /// <param name="lstIds">id列表,如果是联合主键，请使用Where条件</param>
    /// <returns>数据实体列表</returns>
    public List<MesProduct> QueryByIDs(object[] lstIds)
    {
        var _db = Db.Default;
        return _db.MesProducts.Where(d => lstIds.Contains(lstIds)).ToList();
    }

    /// <summary>
    /// 写入实体数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns>插入个数 插入成功为1</returns>
    public int Add(MesProduct entity)
    {
        var _db = Db.Default;
        return _db.MesProducts.Insert(entity);
    }

    /// <summary>
    /// 批量插入实体
    /// </summary>
    /// <param name="listEntity">实体集合</param>
    /// <returns>影响行数</returns>
    public int Add(IEnumerable<MesProduct> listEntity)
    {
        var _db = Db.Default;
        _db.MesProducts.AddRange(listEntity);
        int insertedCount = _db.SaveChanges();
        return insertedCount;
    }
    /// <summary>
    /// 根据实体删除一条数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns></returns>
    public int DeleteById(string id)
    {
        var _db = Db.Default;

        return _db.MesProducts.Where(d => d.Id == id).Delete();
    }

    /// <summary>
    /// 删除指定ID集合的数据(批量删除)
    /// </summary>
    /// <param name="ids">主键ID集合</param>
    /// <returns></returns>
    public int Deletes(IEnumerable<MesProduct> entitys)
    {
        try
        {
            var _db = Db.Default;
            _db.MesProducts.BulkDelete(entitys);
            int result = _db.SaveChanges();
            return result;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }
    /// <summary>
    /// 更新实体数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns></returns>
    public int Update(MesProduct entity)
    {
        var _db = Db.Default;
        return _db.MesProducts.Update<MesProduct>(new MesProduct()
        {
            Id = entity.Id,
            EquipName = entity.EquipName,
            SourceType = entity.SourceType,
            BatchName = entity.BatchName,
            PartNumber = entity.PartNumber,
            Quantity = entity.Quantity,
            ProduceTime = entity.ProduceTime,
            PassFlag = entity.PassFlag,
            CreateTime = entity.CreateTime,
            CreateUser = entity.CreateUser,
            InTime = entity.InTime,
            OutTime = entity.OutTime,
            UpdateTime = entity.UpdateTime,
            UpdateUser = entity.UpdateUser,
            Remarks = entity.Remarks,
            UpdateFlag = entity.UpdateFlag,
            MPartNumber = entity.MPartNumber,
            MPartRevision = entity.MPartRevision,
            StorageNo = entity.StorageNo,
            TraceCode = entity.TraceCode,
            MaterialDesc = entity.MaterialDesc,
            LotNo = entity.LotNo,
            ShiftValue = entity.ShiftValue,
            ClassValue = entity.ClassValue,
            ExpriationTime = entity.ExpriationTime,
            innerdiameter = entity.innerdiameter,
        });
    }
    /// <summary>
    /// 待条件更新所有数据
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <param name="entity"></param>
    /// <returns></returns>
    public int Update(Expression<Func<MesProduct, bool>> whereExpression, MesProduct entity)
    {
        var _db = Db.Default;
        return _db.MesProducts.Where(whereExpression).Update(new MesProduct
        {
            EquipName = entity.EquipName,
            SourceType = entity.SourceType,
            BatchName = entity.BatchName,
            PartNumber = entity.PartNumber,
            Quantity = entity.Quantity,
            Status= entity.Status,
            ProduceTime = entity.ProduceTime,
            PassFlag = entity.PassFlag,
            CreateTime = entity.CreateTime,
            CreateUser = entity.CreateUser,
            InTime = entity.InTime,
            OutTime = entity.OutTime,
            UpdateTime = entity.UpdateTime,
            UpdateUser = entity.UpdateUser,
            Remarks = entity.Remarks,
            UpdateFlag = entity.UpdateFlag,
            MPartNumber = entity.MPartNumber,
            MPartRevision = entity.MPartRevision,
            StorageNo = entity.StorageNo,
            TraceCode = entity.TraceCode,
            MaterialDesc = entity.MaterialDesc,
            LotNo = entity.LotNo,
            ShiftValue = entity.ShiftValue,
            ClassValue = entity.ClassValue,
            ExpriationTime = entity.ExpriationTime,
            innerdiameter = entity.innerdiameter,
        });
    }

    /// <summary>
    /// 正序查询第一条数据
    /// </summary>
    /// <returns></returns>
    public MesProduct First()
    {
        var _db = Db.Default;
        return _db.MesProducts.First();
    }
    /// <summary>
    /// 查询第一条数据
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public MesProduct First(Expression<Func<MesProduct, bool>> whereExpression)
    {
        var _db = Db.Default;
        if (whereExpression == null) return null;
        var list = _db.MesProducts.Where(whereExpression).ToList();
        if (list == null || list.Count <= 0)
        {
            return null;
        }
        return list.OrderByDescending(dd => dd.ProduceTime).First();
    }


    /// <summary>
    /// 功能描述:查询所有数据
    /// 作　　者:Robin
    /// </summary>
    /// <returns>数据列表</returns>
    public List<MesProduct> Query()
    {
        try
        {
            var _db = Db.Default;
            return _db.MesProducts.ToList();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Query执行异常:{ex.Message}");
        }
        return null;
    }


    /// <summary>
    /// 功能描述:查询数据列表
    /// 作　　者:Robin
    /// </summary>
    /// <param name="whereExpression">whereExpression</param>
    /// <returns>数据列表</returns>
    public List<MesProduct> Query(Expression<Func<MesProduct, bool>> whereExpression)
    {
        if (whereExpression == null) return null;
        var _db = Db.Default;
        return _db.MesProducts.Where(whereExpression).OrderByDescending(d=>d.ProduceTime).ToList();
    }


    /// <summary>
    /// 根据sql语句查询
    /// </summary>
    /// <param name="strSql">完整的sql语句</param>
    /// <param name="parameters">参数</param>
    /// <returns>泛型集合</returns>
    public List<MesProduct> QuerySql(string strSql, Parameter[] parameters = null)
    {
        var _db = Db.Default;
        var result = _db.MesProducts.FromSqlRaw(strSql, parameters).ToList();

        return result;
    }
    /// <summary>
    /// 根据sql语句查询 执行update、delete、add
    /// </summary>
    /// <param name="strSql">完整的sql语句</param>
    /// <returns>泛型集合</returns>
    public int ExecuteSqlRaw(string strSql, Parameter[] parameters)
    {
        var dbHelper = new DbHelper();
        dbHelper.CommandText = strSql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        for (int i = 0; i < parameters.Length; i++)
        {
            dbHelper.AddParameter(parameters[i]);
        }
        int rowsReturned = dbHelper.ExecuteNonQuery();

        return rowsReturned;
    }

    #endregion


    /// <summary>
    /// 执行入库更新状态事务
    /// </summary>
    /// <returns></returns>
    public int ExecUpdateStatusTran(MesProduct mesProduct, PORcsLocation rcsLocation)
    {
        var _db = Db.Default;
        int result = 0;
        try
        {
            //添加事务
            using (var transaction = _db.Database.BeginTransaction())
            {
                result = _db.MesProducts.Where(d => d.Id == mesProduct.Id).Update(new MesProduct()
                {
                    Id = mesProduct.Id,
                    Status = mesProduct.Status
                });
                result = _db.RcsLocations.Where(d => d.Id == rcsLocation.Id).Update(new PORcsLocation()
                {
                    TaskId =0,
                    TaskOccupy = 0,
                    TaskOccupyTime = null,
                    LocHasSku = rcsLocation.LocHasSku,
                    LocHasSkuTime = rcsLocation.LocHasSkuTime,
                    MaterialId = rcsLocation.MaterialId,
                    ProductBatch = mesProduct.BatchName,
                    UpdateTime = rcsLocation.UpdateTime,
                    MdTime = rcsLocation.MdTime,
                    SkuRealCount = rcsLocation.SkuRealCount,
                    LocSize = rcsLocation.LocSize,
                    Pid = rcsLocation.Pid,
                });
                _db.SaveChanges();
                transaction.Commit();
                result =2;
            }
            return result;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"执行入库任务更新表失败！原因：【{ex.Message}】" });
        }
        return result;

    }

    public int ExecDeleteByTaskTran(MesProduct mesProduct, POWcsTask wcsTask, POWcsTaskCmd wcsTaskCmd)
    {
        int result = 0;
        try
        {
            var _db=Db.Default;

            wcsTask.TaskWmsStatus = 15;
            wcsTask.RemarkMemo = "检测信号取圈为空删除";
            wcsTaskCmd.TaskWmsStatus = 15;
          

            using (var transaction = _db.Database.BeginTransaction())
            {
                result = _db.WcsTasks.Where(d => d.Id == wcsTask.Id).Delete();
                result = _db.WcsTaskCmds.Where(d => d.Id == wcsTaskCmd.Id).Delete();
                result = _db.MesProducts.Where(d => d.Id == mesProduct.Id).Delete();

                result = _db.BakMesProducts.CopyFrom(mesProduct);
                result = _db.BakWcsTasks.CopyFrom(wcsTask);
                result = _db.BakWcsTaskCmds.CopyFrom(wcsTask);

                _db.SaveChanges();
                transaction.Commit();
                return result;
            }
        }
        catch (Exception)
        {
            return result;
        }
    }
}